#!/bin/bash

# macOS应用安装脚本
# 用途：将Flutter构建的macOS应用安装到应用程序文件夹

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 应用名称（从构建产物中自动查找）
BUILD_DIR="build/macos/Build/Products/Release"
INSTALL_DIR="/Applications"

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  macOS应用安装脚本${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# 获取脚本所在目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# 定义允许的项目列表
ALLOWED_PROJECTS=("sloth-bear-doc" "sloth-bear-todo" "sloth-bear-moments" "sloth-bear-collect")

# 扫描指定的Flutter项目（项目在上级目录）
echo -e "${YELLOW}正在扫描Flutter项目...${NC}"
PROJECTS=()
for project_name in "${ALLOWED_PROJECTS[@]}"; do
    project_dir="$SCRIPT_DIR/../$project_name"
    if [ -f "$project_dir/pubspec.yaml" ]; then
        # 获取绝对路径
        project_dir="$(cd "$project_dir" && pwd)"
        PROJECTS+=("$project_dir|$project_name")
    fi
done

# 检查是否找到项目
if [ ${#PROJECTS[@]} -eq 0 ]; then
    echo -e "${RED}错误: 未找到任何Flutter项目${NC}"
    echo -e "${YELLOW}期望的项目: ${ALLOWED_PROJECTS[*]}${NC}"
    exit 1
fi

# 如果通过命令行参数指定了项目编号，直接使用；否则需要选择
if [ -n "$1" ]; then
    PROJECT_INDEX=$1
    # 验证项目索引
    if [ "$PROJECT_INDEX" -lt 1 ] || [ "$PROJECT_INDEX" -gt ${#PROJECTS[@]} ]; then
        echo -e "${RED}错误: 项目编号 $PROJECT_INDEX 无效（有效范围: 1-${#PROJECTS[@]}）${NC}"
        exit 1
    fi
    IFS='|' read -r PROJECT_DIR PROJECT_NAME <<< "${PROJECTS[$((PROJECT_INDEX-1))]}"
    echo -e "${GREEN}✓ 已选择: ${PROJECT_NAME}${NC}"
else
    # 如果只有一个项目，直接使用
    if [ ${#PROJECTS[@]} -eq 1 ]; then
        IFS='|' read -r PROJECT_DIR PROJECT_NAME <<< "${PROJECTS[0]}"
        echo -e "${GREEN}✓ 找到Flutter项目: ${PROJECT_NAME}${NC}"
    else
        # 多个项目，让用户选择
        echo -e "${YELLOW}找到以下Flutter项目:${NC}"
        for i in "${!PROJECTS[@]}"; do
            IFS='|' read -r _ project_name <<< "${PROJECTS[$i]}"
            echo "  $((i+1)). $project_name"
        done
        echo ""

        # 读取用户选择
        while true; do
            read -p "请选择要安装的项目 (1-${#PROJECTS[@]}): " choice
            if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 1 ] && [ "$choice" -le ${#PROJECTS[@]} ]; then
                break
            fi
            echo -e "${RED}无效选择，请重试${NC}"
        done

        IFS='|' read -r PROJECT_DIR PROJECT_NAME <<< "${PROJECTS[$((choice-1))]}"
        echo -e "${GREEN}✓ 已选择: ${PROJECT_NAME}${NC}"
    fi
fi

echo -e "${YELLOW}项目目录: ${PROJECT_DIR}${NC}"
cd "${PROJECT_DIR}"
echo ""

# 始终重新构建应用以确保可执行文件正确
echo -e "${YELLOW}开始构建macOS应用...${NC}"
echo ""

# 清理之前的构建
flutter clean

# 获取依赖
flutter pub get

# 构建macOS应用
flutter build macos --release

echo ""
echo -e "${GREEN}✓ 构建完成${NC}"

# 自动查找构建的.app文件
APP_BUNDLE=$(find ${BUILD_DIR} -maxdepth 1 -name "*.app" -type d | head -n 1)

if [ -z "$APP_BUNDLE" ]; then
    echo -e "${RED}错误: 构建失败，未找到应用程序包${NC}"
    exit 1
fi

# 获取应用名称（只要文件名部分）
APP_NAME=$(basename "$APP_BUNDLE")
echo -e "${GREEN}✓ 找到应用: ${APP_NAME}${NC}"
echo -e "${YELLOW}   路径: ${APP_BUNDLE}${NC}"
echo ""

# 检查应用程序文件夹中是否已存在同名应用
TARGET_PATH="${INSTALL_DIR}/${APP_NAME}"

if [ -d "${TARGET_PATH}" ]; then
    echo -e "${YELLOW}应用已存在，自动覆盖安装: ${TARGET_PATH}${NC}"
    # 删除旧版本
    echo -e "${YELLOW}正在删除旧版本...${NC}"
    rm -rf "${TARGET_PATH}"
fi

# 复制应用到Applications文件夹
echo ""
echo -e "${GREEN}正在安装应用到 ${INSTALL_DIR}...${NC}"
cp -R "${APP_BUNDLE}" "${INSTALL_DIR}/"

# 检查安装是否成功
if [ -d "${TARGET_PATH}" ]; then
    echo ""
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}  ✓ 安装成功！${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo -e "应用已安装到: ${GREEN}${TARGET_PATH}${NC}"
    echo ""

    # 自动打开应用
    echo -e "${GREEN}正在启动应用...${NC}"
    open "${TARGET_PATH}"
else
    echo -e "${RED}错误: 安装失败${NC}"
    exit 1
fi
